package me.jiatao.kotlinmall.ui.activity

import android.os.Bundle
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.view_toolbar.*
import me.jiatao.baselibrary.common.AppManager
import me.jiatao.baselibrary.data.monitor.NetworkMonitor
import me.jiatao.baselibrary.ui.activity.BaseActivity
import me.jiatao.kotlinmall.R
import me.jiatao.kotlinmall.ui.fragment.HomeFragment
import me.jiatao.kotlinmall.ui.fragment.MeFragment
import org.jetbrains.anko.toast

class MainActivity : BaseActivity() {
    private val BOTTOM_INDEX: String = "bottom_index"
    private val FRAGMENT_HOME = 0
    private val FRAGMENT_SQUARE = 1
    private val FRAGMENT_WECHAT = 2
    private val FRAGMENT_SYSTEM = 3
    private val FRAGMENT_PROJECT = 4
    private var mHomeFragment: HomeFragment? = null
    private var mSquareFragment: MeFragment? = null
    private var mWeChatFragment: MeFragment? = null
    private var mSystemFragment: MeFragment? = null
    private var mProjectFragment: MeFragment? = null
    private var fragmentIndex = FRAGMENT_HOME
    private var pressTime: Long = 0 //记录退出时间

    override fun onCreate(savedInstanceState: Bundle?) {
        if (savedInstanceState != null) {
            fragmentIndex = savedInstanceState.getInt(BOTTOM_INDEX)
        }

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        /**
         * 监听网络状态 放在super.onCreate之后
         */
        NetworkMonitor.getInstance().register(mActivity.application)

        initView()
        initBottomNav()
        showFragment(fragmentIndex)
    }

    override fun onDestroy() {
        //关闭网络状态监听
        NetworkMonitor.getInstance().unRegister()

        /**
         * 释放资源
         */
        mHomeFragment = null
        mSquareFragment = null
        mSystemFragment = null
        mProjectFragment = null
        mWeChatFragment = null

        super.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt(BOTTOM_INDEX, fragmentIndex)
    }


    override fun recreate() {
        try {
            val fragmentTransaction = supportFragmentManager.beginTransaction()
            if (mHomeFragment != null) {
                fragmentTransaction.remove(mHomeFragment!!)
            }
            if (mSquareFragment != null) {
                fragmentTransaction.remove(mSquareFragment!!)
            }
            if (mSystemFragment != null) {
                fragmentTransaction.remove(mSystemFragment!!)
            }
            if (mProjectFragment != null) {
                fragmentTransaction.remove(mProjectFragment!!)
            }
            if (mWeChatFragment != null) {
                fragmentTransaction.remove(mWeChatFragment!!)
            }
            fragmentTransaction.commitAllowingStateLoss()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        super.recreate()
    }


    //region 初始化控件
    /**
     * view 初始化
     */
    private fun initView() {
        toolbar_view.run {
            title = getString(R.string.app_name)
            setSupportActionBar(this)
        }


        initFloatBtn()
        initDrawerLayout()
    }

    /**
     * 绑定浮动按钮点击回到顶部
     */
    private fun initFloatBtn() {
        floating_action_btn.setOnClickListener {
            when (fragmentIndex) {
                FRAGMENT_HOME -> {
                    mHomeFragment?.scrollToTop()
                }
//                FRAGMENT_SQUARE -> {
//                    mSquareFragment?.scrollToTop()
//                }
//                FRAGMENT_SYSTEM -> {
//                    mSystemFragment?.scrollToTop()
//                }
//                FRAGMENT_PROJECT -> {
//                    mProjectFragment?.scrollToTop()
//                }
//                FRAGMENT_WECHAT -> {
//                    mWeChatFragment?.scrollToTop()
//                }
            }
        }
    }

    /**
     * init DrawerLayout
     */
    private fun initDrawerLayout() {
        drawer_layout.run {
            val toggle = ActionBarDrawerToggle(
                this@MainActivity,
                this,
                toolbar_view,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
            )
            addDrawerListener(toggle)
            toggle.syncState()
        }
    }


    //endregion

    /**
     * 展示Fragment
     * @param index
     */
    private fun showFragment(index: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)
        fragmentIndex = index
        when (index) {
            FRAGMENT_HOME // 首页
            -> {
                toolbar_view.title = getString(R.string.app_name)
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance()
                    transaction.add(R.id.main_container, mHomeFragment!!, "home")
                } else {
                    transaction.show(mHomeFragment!!)
                }
                transaction.setPrimaryNavigationFragment(mHomeFragment)
            }
            FRAGMENT_SQUARE  // 广场
            -> {
                toolbar_view.title = getString(R.string.square)
                if (mSquareFragment == null) {
                    mSquareFragment = MeFragment.getInstance()
                    transaction.add(R.id.main_container, mSquareFragment!!, "square")
                } else {
                    transaction.show(mSquareFragment!!)
                }
                transaction.setPrimaryNavigationFragment(mSquareFragment)
            }
            FRAGMENT_SYSTEM // 体系
            -> {
                toolbar_view.title = getString(R.string.knowledge_system)
                if (mSystemFragment == null) {
                    mSystemFragment = MeFragment.getInstance()
                    transaction.add(R.id.main_container, mSystemFragment!!, "system")
                } else {
                    transaction.show(mSystemFragment!!)
                }
                transaction.setPrimaryNavigationFragment(mSystemFragment)
            }
            FRAGMENT_PROJECT // 项目
            -> {
                toolbar_view.title = getString(R.string.project)
                if (mProjectFragment == null) {
                    mProjectFragment = MeFragment.getInstance()
                    transaction.add(R.id.main_container, mProjectFragment!!, "project")
                } else {
                    transaction.show(mProjectFragment!!)
                }
                transaction.setPrimaryNavigationFragment(mProjectFragment)
            }
            FRAGMENT_WECHAT // 公众号
            -> {
                toolbar_view.title = getString(R.string.wechat)
                if (mWeChatFragment == null) {
                    mWeChatFragment = MeFragment.getInstance()
                    transaction.add(R.id.main_container, mWeChatFragment!!, "wechat")
                } else {
                    transaction.show(mWeChatFragment!!)
                }
                transaction.setPrimaryNavigationFragment(mWeChatFragment)
            }
        }
        transaction.commit()
    }

    /**
     * 隐藏所有的Fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
//        mHomeFragment?.let { transaction.hide(it) }
//        mSquareFragment?.let { transaction.hide(it) }
//        mSystemFragment?.let { transaction.hide(it) }
//        mProjectFragment?.let { transaction.hide(it) }
//        mWeChatFragment?.let { transaction.hide(it) }

        /**
         * 获取当前正在显示的fragment
         * 需要调用transaction.setPrimaryNavigationFragment(Fragment)
         * */
        val fragment: Fragment? = supportFragmentManager.primaryNavigationFragment
        if (fragment != null) {
            transaction.hide(fragment)
        }
    }


    /**
     * 初始化底部导航切换事件
     */
    private fun initBottomNav() {
        bottom_nav_bar.setOnNavigationItemSelectedListener { item ->
            //获取菜单 android:orderInCategory
            showFragment(item.order)

            /**
             * 返回true 标识被选中,改变按钮状态
             * 返回false 标识未选中
             **/
            true
        }
    }


    /**
     *  重写Back事件，双击退出
     */
    override fun onBackPressed() {
        val time = System.currentTimeMillis()
        if (time - pressTime > 2000) {
            toast("再按一次退出程序")
            pressTime = time
        } else {
            AppManager.instance.exitApp(this)
        }
    }
}
